package com.yincheng.oes.business.schedule;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

/**
 * @Description 定时任务管理器
 * @Author 446948434@qq.com
 * @Date 2021/11/6 3:32 下午
 * @Version 1.0
 */
@Component
public class ScheduleManager {
    /**
     * 日志
     */
    private static final Logger logger = LogManager.getLogger(ScheduleManager.class);

    /**
     * 定时任务间隔周期 one day
     */
    private static final Long PERIOD = 1000 * 60 * 60 * 24L;

    @Autowired
    private CleanTmpFileTask cleanTmpFileTask;

    @PostConstruct
    public void init() throws Exception {
        logger.debug("start execute schedule task");
        doCleanTmpFile();
    }

    private void doCleanTmpFile() {
        Timer timer = new Timer();
        timer.schedule(cleanTmpFileTask, buildTime(), PERIOD);
    }

    private static Date buildTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 1);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date time = calendar.getTime();
        if (time.before(new Date())) {
//            若果当前时间已经是凌晨1点后，需要往后加1天，否则任务会立即执行。
            time = addDay(time, 1);
        }
        return time;
    }

    private static Date addDay(Date date, int days) {
        Calendar startDT = Calendar.getInstance();
        startDT.setTime(date);
        startDT.add(Calendar.DAY_OF_MONTH, days);
        return startDT.getTime();
    }
}
